
import type { FormProps } from 'antd';
import { Button, Form, Input, Checkbox } from 'antd';
import { NavBar } from 'antd-mobile';
import axios from '../../api/http'
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import title from '../../assets/title.png'

type FieldType = {
  phone?: string;
  code?: string;
  agree?: boolean;
};

function Index() {
  const nav = useNavigate();
  const [countdown, setCountdown] = useState(0);
  const [randomCode, setRandomCode] = useState('');
  const [form] = Form.useForm();
  const [displayCode, setDisplayCode] = useState<string | null>(null);
  
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    // if(!values.phone){
    //   alert('请输入手机号');
    //   return;
    // }
    // if(!values.code){
    //   alert('请输入验证码');
    //   return;
    // }
    // if(!values.agree){
    //   alert('请同意服务协议');
    //   return;
    // }
    
    // 先在前端校验短信验证码（与生成的随机验证码一致即可）
    if(values.code !== randomCode){
      alert('验证码不正确');
      return;
    }

    // 调用真实后端登录接口
    console.log('发送登录请求:', values);
    axios.post('/login', values).then(res => {
      // 兼容两种返回结构：{code, data} 或 {status, data}
      const businessCode = (res && (res as any).code) as number | undefined;
      const token = (res as any)?.data?.token || (res as any)?.token;

      if (businessCode === 20000 || token) {
        localStorage.setItem('token', token || '');
        console.log('登录成功，跳转到home页面');
        nav('/home');
      } else {
        console.log('登录失败，返回数据:', res);
        alert('登录失败');
      }
    }).catch((error) => {
      console.error('登录请求失败:', error);
      alert('登录失败');
    });
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const sendCode = () => {
    if(countdown > 0) return;
    setCountdown(5);
    setDisplayCode(null);
    
    // 生成6位随机数字验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    setRandomCode(code);
    console.log('生成的验证码:', code);
    
    const timer = setInterval(() => {
      setCountdown(prev => {
        if(prev <= 1) {
          clearInterval(timer);
          // 倒计时结束后，回显验证码（不自动填充输入框）
          console.log('倒计时结束，回显验证码:', code);
          setDisplayCode(code);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };
  return (
    <div style={{backgroundColor:'#fff',minHeight:'100vh'}}>
      <NavBar onBack={() => nav(-1)} />
      
      <div style={{textAlign:'center',padding:'20px'}}>
        <img src={title} alt="妙手医生" style={{width:'200px',height:'auto',marginBottom:'40px'}}/>
      </div>

      <div style={{padding:'0 24px'}}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item name="phone">
            <div style={{
              display:'flex',
              alignItems:'center',
              borderBottom:'1px solid #d9d9d9',
              paddingBottom:'12px',
              marginBottom:'20px'
            }}>
              <span style={{marginRight:'8px',color:'#666'}}>+86</span>
              <Input
                placeholder="输入手机号"
                style={{border:'none',boxShadow:'none',flex:1}}
                bordered={false}
              />
            </div>
          </Form.Item>

          <Form.Item name="code">
            <div style={{
              display:'flex',
              alignItems:'center',
              borderBottom:'1px solid #d9d9d9',
              paddingBottom:'12px',
              marginBottom:'20px'
            }}>
              {displayCode && countdown === 0 && (
                <span style={{marginRight:'8px', color:'#1677ff', fontSize:'12px'}}>验证码: {displayCode}</span>
              )}
              <Input
                placeholder="输入验证码"
                style={{border:'none',boxShadow:'none',flex:1}}
                bordered={false}
              />
              <Button
                type="primary"
                size="small"
                style={{
                  background:countdown > 0 ? '#ccc' : '#1677ff',
                  border:'none',
                  borderRadius:'4px',
                  padding:'4px 12px',
                  fontSize:'12px'
                }}
                disabled={countdown > 0}
                onClick={sendCode}
              >
                {countdown > 0 ? `${countdown}s` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{
                width:'100%',
                height:'48px',
                background:'#1677ff',
                border:'none',
                borderRadius:'24px',
                fontSize:'16px',
                marginTop:'20px'
              }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div style={{
          display:'flex',
          alignItems:'flex-start',
          marginTop:'40px',
          padding:'0 8px'
        }}>
          <Checkbox style={{marginTop:'2px'}} />
          <div style={{
            fontSize:'12px',
            color:'#666',
            lineHeight:'1.4',
            marginLeft:'8px'
          }}>
            已阅读并同意
            <span style={{color:'#1677ff'}}>《妙手医生服务协议》</span>
            和
            <span style={{color:'#1677ff'}}>《妙手医生隐私政策》</span>
            、
            <span style={{color:'#1677ff'}}>《妙手医生儿童个人信息保护规则》</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Index
